package edu.usc.cmb.iregulome.job;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ResourceBundle;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;

import edu.usc.cmb.iregulome.entity.Sample;

/**
 * @author hsy541
 * 
 *         This runnable includes some method for a thread to execute the
 *         download task of the dataset
 * 
 */
public class FileDownloadJob implements Runnable {

	private static BlockingQueue<Sample> samples = new LinkedBlockingQueue<Sample>();

	private final FTPClient client = new FTPClient();

	private static ResourceBundle bundler = ResourceBundle.getBundle("app");

	private static final Logger log = Logger.getLogger(FileDownloadJob.class);

	public FileDownloadJob() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void run() {

		while (true) {
			try {
				String baseDir = bundler
						.getString("iregulome.sample.download.basedir");
				File baseDirF = new File(baseDir);
				if (!baseDirF.exists()) {
					baseDirF.mkdirs();
				}

				Sample sample = samples.take();

				log.info("Downloading..." + sample.getId());

				String url = sample.getUrl();

				client.connect(url.substring(0, url.indexOf("/")));
				client.login("anonymous", "anonymous");
				client.enterLocalPassiveMode();
				client.setFileType(FTPClient.BINARY_FILE_TYPE);
				client.changeWorkingDirectory(url.substring(url.indexOf("/"),
						url.length()));

				String subFolderName = "";

				String type = sample.getStudy().getType();
				subFolderName += type + File.separator + sample.getId();
				File downloadDir = new File(baseDirF, subFolderName);
				if (!downloadDir.exists()) {
					downloadDir.mkdirs();
				}
				FTPFile[] file = client.listFiles();
				for (FTPFile ftpFile : file) {
					client.retrieveFile(ftpFile.getName(),
							new FileOutputStream(new File(downloadDir, ftpFile
									.getName())));
				}

				log.info("Done..." + sample.getId());

			} catch (Exception e) {
				log.error("Download dataset error: " + e);
			} finally {
				try {
					if (client.isConnected()) {
						client.disconnect();
					}
				} catch (IOException e) {
				}
			}
		}

	}

	public static final void putIds(Sample sample) {
		try {
			samples.put(sample);
		} catch (InterruptedException e) {
			log.error("Download dataset error: " + e);
		}
	}
}
